package com.ywl.service.impl;

import com.ywl.common.ResponseResult;
import com.ywl.domain.LoginUser;
import com.ywl.domain.User;
import com.ywl.service.LoginService;
import com.ywl.utlis.JwtUtil;
import com.ywl.utlis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 24040
 * @name LoginServiceImpl
 * @date 2022-10-16 10:01
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //1.AuthenticationManager 中的authenticate方法进行用户认证
        //创建Authentication 对象，传入用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());

        //需要传入authenticate对象
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //2.如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登陆失败");
        }

        //3.如果认证通过了，使用userId 生成一个jwt jwt存入ResponseResult
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);

        //4.把完整的用户信息存入redis中
        redisCache.setCacheObject("login:"+userId,loginUser);
        return new ResponseResult(200,"登陆成功",map);
    }

    /**
     * 退出
     * @return
     */
    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        //删除redis中的值
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+id);
        return new ResponseResult(200,"注销成功");
    }
}
